package com.medicinezp.baseconfig.service.impl;

import java.util.*;
import java.util.concurrent.TimeUnit;

import cn.hutool.http.HttpUtil;
import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.medicinezp.baseconfig.domain.BaseJobs;
import com.medicinezp.baseconfig.domain.BaseUserJobApplyLogs;
import com.medicinezp.baseconfig.mapper.BaseUserJobApplyLogsMapper;
import com.medicinezp.baseconfig.service.IBaseJobsService;
import com.medicinezp.common.config.MedicinezpConfig;
import com.medicinezp.common.core.domain.entity.SysUser;
import com.medicinezp.common.core.redis.RedisCache;
import com.medicinezp.common.utils.DateUtils;
import com.medicinezp.common.utils.SecurityUtils;
import com.medicinezp.common.utils.StringUtils;
import com.medicinezp.system.service.ISysUserService;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.medicinezp.baseconfig.mapper.BaseUserJobApplyMapper;
import com.medicinezp.baseconfig.domain.BaseUserJobApply;
import com.medicinezp.baseconfig.service.IBaseUserJobApplyService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 用户投递简历申请Service业务层处理
 *
 * @author medicinezp
 * @date 2022-09-22
 */
@Service
public class BaseUserJobApplyServiceImpl implements IBaseUserJobApplyService
{
    private static Logger logger = LoggerFactory.getLogger(BaseUserJobApplyServiceImpl.class);
    @Autowired
    private BaseUserJobApplyMapper baseUserJobApplyMapper;

    @Autowired
    private BaseUserJobApplyLogsMapper baseUserJobApplyLogsMapper;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private MedicinezpConfig medicinezpConfig;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private IBaseJobsService baseJobsService;

    /**
     * 查询用户投递简历申请
     *
     * @param id 用户投递简历申请主键
     * @return 用户投递简历申请
     */
    @Override
    public BaseUserJobApply selectBaseUserJobApplyById(Long id)
    {
        return baseUserJobApplyMapper.selectBaseUserJobApplyById(id);
    }

    /**
     * 查询用户投递简历申请列表
     *
     * @param baseUserJobApply 用户投递简历申请
     * @return 用户投递简历申请
     */
    @Override
    public List<BaseUserJobApply> selectBaseUserJobApplyList(BaseUserJobApply baseUserJobApply)
    {
        return baseUserJobApplyMapper.selectBaseUserJobApplyList(baseUserJobApply);
    }

    /**
     * 新增用户投递简历申请
     *
     * @param baseUserJobApply 用户投递简历申请
     * @return 结果
     */
    @Transactional
    @Override
    public int insertBaseUserJobApply(BaseUserJobApply baseUserJobApply)
    {
        int result= baseUserJobApplyMapper.insertBaseUserJobApply(baseUserJobApply);
        if(result>0){
            BaseUserJobApplyLogs logs=new BaseUserJobApplyLogs();
            logs.setApplyId(baseUserJobApply.getId());
            logs.setContent("投递简历");
            logs.setCreateTime(DateUtils.getNowDate());
            logs.setDealTime(DateUtils.getNowDate());
            logs.setCreateBy(SecurityUtils.getUsername());
            baseUserJobApplyLogsMapper.insertBaseUserJobApplyLogs(logs);
        }
        return result;
    }

    /**
     * 修改用户投递简历申请
     *
     * @param baseUserJobApply 用户投递简历申请
     * @return 结果
     */
    @Override
    public int updateBaseUserJobApply(BaseUserJobApply baseUserJobApply)
    {
        return baseUserJobApplyMapper.updateBaseUserJobApply(baseUserJobApply);
    }

    /**
     * 批量删除用户投递简历申请
     *
     * @param ids 需要删除的用户投递简历申请主键
     * @return 结果
     */
    @Override
    public int deleteBaseUserJobApplyByIds(Long[] ids)
    {
        return baseUserJobApplyMapper.deleteBaseUserJobApplyByIds(ids);
    }

    /**
     * 删除用户投递简历申请信息
     *
     * @param id 用户投递简历申请主键
     * @return 结果
     */
    @Override
    public int deleteBaseUserJobApplyById(Long id)
    {
        return baseUserJobApplyMapper.deleteBaseUserJobApplyById(id);
    }

    @Override
    public List<BaseUserJobApply> selectCompanyUserJobApplyList(BaseUserJobApply jobApply) {
        if(StringUtils.isNotEmpty(jobApply.getJobIds())){
            String jobids="'"+jobApply.getJobIds().replaceAll(",","','")+"'";
            jobApply.setJobIds(jobids);
        }else{
            jobApply.setJobIds(null);
        }
        return baseUserJobApplyMapper.selectCompanyUserJobApplyList(jobApply);
    }

    @Override
    @Transactional
    public int approveUserJobApply(BaseUserJobApply baseUserJobApply) {
        baseUserJobApply.setApplyStatus(baseUserJobApply.getApproveStatus());
        int result=baseUserJobApplyMapper.updateBaseUserJobApply(baseUserJobApply);
        if(result>0){
            String title="";
            if("02".equals(baseUserJobApply.getApproveStatus())){
                title="继续沟通";
            }
            else if("03".equals(baseUserJobApply.getApproveStatus())){
                title="不合适";
            }
            else if("04".equals(baseUserJobApply.getApproveStatus())){
                title="邀请面试";
            }
            else if("05".equals(baseUserJobApply.getApproveStatus())){
                title="面试通过";
            }
            else if("06".equals(baseUserJobApply.getApproveStatus())){
                title="面试未通过";
            }
            BaseUserJobApplyLogs logs=new BaseUserJobApplyLogs();
            logs.setApplyId(baseUserJobApply.getId());
            logs.setContent(title);
            logs.setCreateTime(DateUtils.getNowDate());
            logs.setDealTime(DateUtils.getNowDate());
            logs.setCreateBy(SecurityUtils.getUsername());
            baseUserJobApplyLogsMapper.insertBaseUserJobApplyLogs(logs);


            BaseUserJobApply apply=selectBaseUserJobApplyById(baseUserJobApply.getId());
            SysUser user=userService.selectUserById(apply.getUserId());
            BaseJobs jobInfo=baseJobsService.selectBaseJobsById(apply.getJobId());

            Map<String,Object> data = new HashMap<>();
            Map<String,Object> value = new HashMap();
            value.put("value", "简历投递通知");
            data.put("thing1",value);

            Map<String,Object> value1 = new HashMap();
            value1.put("value", "您投递"+jobInfo.getJobName()+"岗位，已经处理");
            //value1.put("value", "公区儿童游玩区故障");
            data.put("thing2",value1);

            Map<String,Object> value2 = new HashMap();
            value2.put("value",title);
            data.put("phrase4",value2);

            Map<String,Object> value3 = new HashMap();
            String s = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, DateUtils.getNowDate());
            value3.put("value",s);
            data.put("time3",value3);

            Map<String, Object> tokenMap=getAccessToken();
            String wxAccessToken=String.valueOf(tokenMap.get("access_token"));
            Map<String, Object> body = new HashMap<>();
            body.put("access_token ",wxAccessToken );
            body.put("touser", user.getOpenId());
            body.put("template_id","H2O4Gx-uR3BxbscqUY1hn5HeHLHg0tFNLrLWSyfItDM");
//        body.put("miniprogram_state","trial");
            body.put("page","pages/tabbar/message");
            body.put("data", JSON.toJSON(data));
//        log.info(JSON.toJSONString(data));
            String res = HttpUtil.post("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token="+wxAccessToken, JSONUtils.toJSONString(body));
            logger.info(res);
        }
        return result;
    }

    public Map<String, Object> getAccessToken() {
        Map<String, Object> access_token = redisCache.getCacheMap("zp_access_token");
        if (StringUtils.isNotNull(access_token) && StringUtils.isNotEmpty(access_token)) {
            return access_token;
        }
        //拼接url
        StringBuilder url = new StringBuilder("https://api.weixin.qq.com/cgi-bin/token?");
        //appid设置
        url.append("grant_type=");
        url.append("client_credential");
        //secret设置
        url.append("&appid=");
        url.append(medicinezpConfig.getAppId());
        //code设置
        url.append("&secret=");
        url.append(medicinezpConfig.getAppSecret());
        Map<String, Object> map = null;
        try {
            //构建一个Client
            HttpClient client = HttpClientBuilder.create().build();
            //构建一个GET请求
            HttpGet get = new HttpGet(url.toString());
            //提交GET请求
            HttpResponse response = client.execute(get);
            //拿到返回的HttpResponse的"实体"
            HttpEntity result = response.getEntity();
            String content = EntityUtils.toString(result);
            //打印返回的信息
            System.out.println(content);
            //把信息封装为json
            JSONObject res = JSONObject.parseObject(content);
            //把信息封装到map
            map = parseJSON2Map(res);
            redisCache.setCacheMap("zp_access_token", map);
            Integer expiresIn = (Integer) map.get("expires_in");
            int expire = expiresIn - 200;

            boolean flag = redisCache.expire("zp_access_token", Long.valueOf(expire), TimeUnit.SECONDS);
            if (!flag) {
                redisCache.deleteObject("zp_access_token");
            }


        } catch (Exception e) {
            logger.info("获取getAccessToken失败:{}", e.getMessage());
        }
        return map;
    }

    public static Map<String, Object> parseJSON2Map(JSONObject json) {
        Map<String, Object> map = new HashMap<String, Object>();
        // 最外层解析
        for (Object k : json.keySet()) {
            Object v = json.get(k);
            // 如果内层还是数组的话，继续解析
            if (v instanceof JSONArray) {
                List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
                @SuppressWarnings("unchecked")
                Iterator it = ((JSONArray) v).iterator();
                while (it.hasNext()) {
                    JSONObject json2 = (JSONObject) it.next();
                    list.add(parseJSON2Map(json2));
                }
                map.put(k.toString(), list);
            } else {
                map.put(k.toString(), v);
            }
        }
        return map;
    }

    @Override
    public List<BaseUserJobApply> selectAllUserJobApplyList(BaseUserJobApply baseUserJobApply) {
        return baseUserJobApplyMapper.selectAllUserJobApplyList(baseUserJobApply);
    }
}
